package com.tiance.web.controller.front;

import com.alibaba.fastjson.JSON;
import com.tiance.constants.CommonConstants;
import com.tiance.dal.dataobject.TaskDO;
import com.tiance.domainservice.checker.MemberParamsChecker;
import com.tiance.domainservice.domain.TaskDomain;
import com.tiance.domainservice.service.TaskService;
import com.tiance.enums.EntityTypeEnum;
import com.tiance.enums.ErrorCodeEnum;
import com.tiance.enums.OperateTypeEnum;
import com.tiance.exception.BusinessException;
import com.tiance.integration.cache.MapCacheUtil;
import com.tiance.page.QueryPage;
import com.tiance.utils.BeanConverterUtil;
import com.tiance.utils.DateUtils;
import com.tiance.utils.Validator;
import com.tiance.vo.TaskVO;
import com.tiance.web.aspect.OperatorControllerLog;
import com.tiance.web.controller.base.FrontController;
import com.tiance.web.controller.common.BaseResponse;
import com.tiance.web.convertor.ModelConvert;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author 雷霆
 * @version 1.0.0
 * @date$ 2019/1/30
 *
 * Description：任务管理
 *
 * Modification History:
 *
 */
@Controller
@RequestMapping(value = "/front/task")
public class TaskController extends FrontController {
    @Autowired
    private TaskService taskService;

    @RequestMapping(value = "/toAccepttesk.action",method = RequestMethod.GET)
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="")
    public String toAccepttesk() {
        return "/front/accepttesk";
    }
    @RequestMapping(value = "/toAcceptteskresult.action",method = RequestMethod.GET)
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="")
    public String toAcceptteskresult() {
        return "/front/acceptteskresult";
    }

    private static String LOG_PREFIX ="TaskController| 任务控制器===>";




    @RequestMapping(value = "/querySignUpTaskList.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType=OperateTypeEnum.FRONT_INTERFACE,operationName="查询会员承接的任务列表")
    public BaseResponse querySignUpTaskList(HttpServletRequest request, TaskVO taskVO, QueryPage queryPage){
        logger.info("开始查询会员承接的任务列表，请求参数:{}", JSON.toJSONString(taskVO));

        BaseResponse<TaskVO> backResponse=new BaseResponse<>();
        try {
            MemberParamsChecker.checkPageQuery(queryPage);
            taskVO.setQueryPage(queryPage);

            HttpSession session=request.getSession();
            Object memberId=session.getAttribute(CommonConstants.MEMBER_ID);
            if(null!=memberId){
                taskVO.setApplicantId((Long)memberId);
            }

            TaskDomain taskDomain= ModelConvert.taskVO2TaskDomain(taskVO);
            List<TaskDO> taskDOList= taskService.querySignUpTaskList(taskDomain);

            List<TaskVO> taskVOList=new ArrayList<>(taskDOList.size());
            if(!CollectionUtils.isEmpty(taskDOList)){
                for(TaskDO taskDO:taskDOList){
                    TaskVO taskVO1=new TaskVO();
                    BeanConverterUtil.copyProperties(taskVO1, taskDO);
                    if(null!=taskDO.getCreateTime()){
                        taskVO1.setCreateTimeStr(DateUtils.getYYYY_MM_DD_HH_MM_SS(taskDO.getCreateTime()));
                    }
                    if(null!=taskDO.getUpdateTime()){
                        taskVO1.setUpdateTimeStr(DateUtils.getYYYY_MM_DD_HH_MM_SS(taskDO.getUpdateTime()));
                    }

                    taskVOList.add(taskVO1);
                }
            }

            backResponse.setResultList(taskVOList);
            backResponse.setQueryPage(taskDomain.getQueryPage());
            backResponse.setTotalRecord(taskDOList.size());
            backResponse.setResponseCode(ErrorCodeEnum.SUCCESS.getCode());
            backResponse.setSuccess(true);
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"查询任务申请列表失败，失败原因：",e1);
            backResponse.setSuccess(false);
            backResponse.setMessage(e1.getMessage());
        }catch (Exception e2){
            logger.error(LOG_PREFIX+"查询任务申请列表失败,失败原因",e2);
            backResponse.setSuccess(false);
            backResponse.setMessage("查询任务申请列表失败");
        }
        logger.info("结束查询会员承接的任务列表，返回数据:{}", JSON.toJSONString(backResponse));
        return  backResponse;

    }



    @RequestMapping(value = "/cancelTask.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="取消任务")
    public BaseResponse cancelTask(TaskVO taskVO){
        logger.info("开始取消任务，请求参数:{}", JSON.toJSONString(taskVO));
        BaseResponse backResponse=new BaseResponse<>();

        try {
            Validator.assertNull(taskVO.getId(),"任务ID不能为空!");
            TaskDomain taskDomain= ModelConvert.taskVO2TaskDomain(taskVO);
            if(MapCacheUtil.lock(taskVO.getId() + EntityTypeEnum.TASK.getCode())) {
                taskService.cancel(taskDomain);
            }else {
                throw new BusinessException("该任务正在操作中，请稍后再试!");
            }
            backResponse.setSuccess(true);
            backResponse.setResponseCode(ErrorCodeEnum.SUCCESS.getCode());
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"取消任务失败，失败原因：",e1);
            backResponse.setSuccess(false);
            backResponse.setMessage(e1.getMessage());
        }catch (Exception e2){
            logger.error(LOG_PREFIX+"取消任务失败,失败原因",e2);
            backResponse.setSuccess(false);
            backResponse.setMessage("取消任务失败");
        }finally {
            MapCacheUtil.unlock(taskVO.getId()+EntityTypeEnum.TASK.getCode());
        }
        logger.info("结束取消任务，返回数据:{}", JSON.toJSONString(backResponse));
        return  backResponse;

    }


    @RequestMapping(value = "/finishTask.action",method = RequestMethod.POST)
    @ResponseBody
    @OperatorControllerLog(operationLogType= OperateTypeEnum.FRONT_INTERFACE,operationName="结束任务")
    public BaseResponse finishTask( TaskVO taskVO){
        logger.info("开始结束任务，请求参数:{}", JSON.toJSONString(taskVO));
        BaseResponse backResponse=new BaseResponse<>();

        try {
            Validator.assertNull(taskVO.getId(),"任务ID不能为空!");
            TaskDomain taskDomain= ModelConvert.taskVO2TaskDomain(taskVO);
            if(MapCacheUtil.lock(taskVO.getId() + EntityTypeEnum.TASK.getCode())) {
                taskService.finish(taskDomain);
            }else {
                throw new BusinessException("该任务正在操作中，请稍后再试!");
            }
            backResponse.setSuccess(true);
            backResponse.setResponseCode(ErrorCodeEnum.SUCCESS.getCode());
        }catch(BusinessException e1){
            logger.info(LOG_PREFIX+"结束任务失败，失败原因：",e1);
            backResponse.setSuccess(false);
            backResponse.setMessage(e1.getMessage());
        }catch (Exception e2){
            logger.error(LOG_PREFIX+"结束任务失败,失败原因",e2);
            backResponse.setSuccess(false);
            backResponse.setMessage("结束任务失败");
        }finally {
            MapCacheUtil.unlock(taskVO.getId()+EntityTypeEnum.TASK.getCode());
        }
        logger.info("结束结束任务，返回数据:{}", JSON.toJSONString(backResponse));
        return  backResponse;

    }
}